class OrderMadePayment < ActiveRecord::Base
   validates :order_item_id,
    :order_made_id,
    :presence => true
  validates :how_much,
    :numericality => {
      :greater_than_or_equal_to => 0
    }

  belongs_to :order_item
  belongs_to :order_made
  belongs_to :updated_by_user, :class_name => 'User', :foreign_key => :updated_by_user_id
  belongs_to :feed
  has_many :feeds, :dependent => :destroy, :order => 'position asc'

  after_create do |payment|
    Feed::PaymentCreated.create!(
      :order_item_id => payment.order_item_id,
      :order_made_id => payment.order_made_id,
      :order_made_payment_id => payment.id)
  end

  before_save do |payment|
    payment.updated_by_user_id = User.current_id if payment.changed?
  end

  after_save do |payment|
    payment.order_item.order.update_attribute(:payed_on, payment.payed_on) if payment.order_item.order.payed_on.nil? or payment.order_item.order.payed_on < payment.payed_on
  end

  def self.how_much_sum(order_id)
    OrderMadePayment.where('order_items.order_id = ?', order_id).includes(:order_item).sum(:how_much)
  end

  def reset_feed!
    update_attributes :feed_id => Feed.where(:order_made_payment_id => id).last.try(:id)
  end
end
